//
//  ChannelViewController.m
//  ZYTS-iPhone
//
//  Created by yuzhou on 12-12-7.
//  Copyright (c) 2012年 wzyk. All rights reserved.
//

#import "ChannelViewController.h"
#import "ChannelBookCell.h"
#import "BookViewController.h"
#import "PlayerBarView.h"
#import "artistCell.h"
#import "ArtistWorkViewController.h"
#import "ChannelSelectView.h"

@interface ChannelViewController ()
{
    BOOL isArtistsShowing;
}
@property (nonatomic,retain) ChannelSelectView *channelSelectView;
@end

@implementation ChannelViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotChannel:) name:gotChannelNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotArtists:) name:gotArtistsNotify object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didSelectCategory:) name:kShowChannel object:nil];
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    self.channelSelectView = [[[NSBundle mainBundle] loadNibNamed:@"ChannelSelectView" owner:self options:nil] objectAtIndex:0];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    bookGridView.requiresSelection = NO;
    bookGridView.backgroundViewExtendsUp = YES;
    bookGridView.backgroundViewExtendsDown = YES;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 6.0) {
        artistsTableView.sectionIndexColor = [UIColor whiteColor];
    }
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        artistsTableView.sectionIndexBackgroundColor = [UIColor clearColor];
    }
    [self updatePlayerBar];
    
    //获取上次查看的频道
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrentCategory];
    if (dic != nil && [dic isKindOfClass:[NSDictionary class]]) {
        [self updateDisplayWithChannel:dic];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:kCurrentCategory];
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
        [self showCategorySelectView];
    }
}

- (IBAction)showCategorySelectView
{
    NSLog(@">>>>>>>");
    _channelSelectView.frame = self.view.window.bounds;
    [_channelSelectView updateDisplay];
    
    [self.view.window addSubview:_channelSelectView];
    NSLog(@">>>>>>>");
}

- (void)updatePlayerBar {
    // 判断是否正在播放
    if ([CollectionData hasContent:kCollection_playing]) {
        if (playerBarView) {
            return;
        }
        
        playerBarView = [[[NSBundle mainBundle] loadNibNamed:@"PlayerBarView" owner:self options:nil] objectAtIndex:0];
        CGRect frameTable = contentView.frame;
        CGRect frameBar = playerBarView.frame;
        frameBar.origin.x = frameTable.origin.x;
        frameBar.origin.y = frameTable.origin.y;
        playerBarView.frame = frameBar;
        [self.view addSubview:playerBarView];
        
        frameTable.origin.y += PlayerBarHeight;
        frameTable.size.height -= PlayerBarHeight;
        contentView.frame = frameTable;
    }
    else if (playerBarView) {
        [playerBarView removeFromSuperview];
        playerBarView = nil;
        
        CGRect frameTable = contentView.frame;
        frameTable.origin.y -= PlayerBarHeight;
        frameTable.size.height += PlayerBarHeight;
        contentView.frame = frameTable;
    }
}

- (void)didSelectCategory:(NSNotification *)notification
{
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        [self updateDisplayWithChannel:notification.object];
    }
}

- (void)updateDisplayWithChannel:(NSDictionary *)dic
{
    self.channelInfo = dic;
//    titleLabel.text = [dic valueForKey:@"class_name"];
    [categoryButton setTitle:[dic valueForKey:@"class_name"] forState:UIControlStateNormal];
    
    if ([[dic valueForKey:@"class_id"] isEqualToString:@"artists"]) {
        isArtistsShowing = YES;
        artistsTableView.hidden = NO;
        bookGridView.hidden = YES;
        [[DataRequest sharedRequest] getArtists];
        [self showLoadingView];
    }
    else {
        isArtistsShowing = NO;
        artistsTableView.hidden = YES;
        bookGridView.hidden = NO;
        [[DataRequest sharedRequest] getChannelByID:[dic valueForKey:@"class_id"]];
        [self showLoadingView];
    }
    //设置当前频道
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:kCurrentCategory];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)gotArtists:(NSNotification *)notification
{
    [self removeloadingView];
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
//            NSLog(@">>>>>>>%@",result);
            self.artistsArray = [NSMutableArray array];
            self.initialsArray = [NSMutableArray array];
            NSString *currentInitial = nil;
            NSMutableArray *initialArray;
            for (NSDictionary *dic in result) {
                if (currentInitial == nil) {
                    initialArray = [NSMutableArray array];
                    [initialArray addObject:dic];
//                    NSLog(@">>>%@",initialArray);
                    currentInitial = [dic valueForKey:@"broadcast_headletter"];
                    [self.initialsArray addObject:currentInitial];
                }
                else if (![[dic valueForKey:@"broadcast_headletter"] isEqualToString:currentInitial]) {
                    [self.artistsArray addObject:initialArray];
                    initialArray = [NSMutableArray array];
                    [initialArray addObject:dic];
//                    NSLog(@">>>%@",initialArray);
                    currentInitial = [dic valueForKey:@"broadcast_headletter"];
                    [self.initialsArray addObject:currentInitial];
                }
                else if ([[dic valueForKey:@"broadcast_headletter"] isEqualToString:currentInitial]) {
                    [initialArray addObject:dic];
                }
            }
            if (initialArray.count > 0) {
                [self.artistsArray addObject:initialArray];
            }
//            NSLog(@">>>>>>%@",self.artistsArray);
//            NSLog(@">>>>>>%@",self.initialsArray);
            [artistsTableView reloadData];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.initialsArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.artistsArray objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    artistCell *cell = [tableView dequeueReusableCellWithIdentifier:@"artistCell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"artistCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.infoDic = [[self.artistsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    [cell updateDisplay];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 94;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    return [self.initialsArray objectAtIndex:section];
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    NSString *title = [self.initialsArray objectAtIndex:section];
//    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)] autorelease];
//    label.textColor = [UIColor whiteColor];
//    label.font = [UIFont boldSystemFontOfSize:15];
//    label.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.7];
//    label.text = [NSString stringWithFormat:@"  %@",title];
//    return label;
//}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.initialsArray;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return index;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ArtistWorkViewController *artistWorkViewController = [[[ArtistWorkViewController alloc] initWithNibName:@"ArtistWorkViewController" bundle:nil] autorelease];
    artistWorkViewController.artistInfo = [[self.artistsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:artistWorkViewController animated:YES];
}

- (void)gotChannel:(NSNotification *)notification
{
    [self removeloadingView];
    if ([notification.object isKindOfClass:[NSDictionary class]]) {
        NSArray *result = [notification.object valueForKey:@"result"];
        if ([result isKindOfClass:[NSArray class]]) {
            self.bookArray = result;
            [bookGridView reloadData];
        }
    }
}

- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView
{
    return self.bookArray.count;
}

- (AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index
{
    ChannelBookCell *cell = (ChannelBookCell *)[bookGridView dequeueReusableCellWithIdentifier:@"ChannelBookCell"];
    if (cell == nil) {
        cell = [[ChannelBookCell alloc] initWithFrame:CGRectMake(0, 0, 96, 128) reuseIdentifier:@"ChannelBookCell"];
        cell.selectionStyle = AQGridViewCellSelectionStyleBlue;
    }
    cell.bookInfo = [self.bookArray objectAtIndex:index];
    [cell updateDisplay];
    return cell;
}

- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index
{
    NSDictionary *bookInfo = [self.bookArray objectAtIndex:index];
    BookViewController *bookViewController = [[[BookViewController alloc] initWithNibName:@"BookViewController" bundle:nil] autorelease];
    bookViewController.itemid = [bookInfo valueForKey:@"item_id"];
    bookViewController.itemname = [bookInfo valueForKey:@"item_name"];
    
    UINavigationController *navController = (UINavigationController *)self.view.window.rootViewController;
    [navController pushViewController:bookViewController animated:YES];
    
    [gridView deselectItemAtIndex:index animated:NO];
}

- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:contentView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [titleLabel release];
    [bookGridView release];
    [_channelInfo release];
    [_artistsArray release];
    [_bookArray release];
    [artistsTableView release];
    [contentView release];
    [categoryButton release];
    [_channelSelectView release];
    [super dealloc];
}
- (void)viewDidUnload {
    [titleLabel release];
    titleLabel = nil;
    [bookGridView release];
    bookGridView = nil;
    playerBarView = nil;
    [artistsTableView release];
    artistsTableView = nil;
    [contentView release];
    contentView = nil;
    [categoryButton release];
    categoryButton = nil;
    [_channelSelectView release];
    _channelSelectView = nil;
    [super viewDidUnload];
}
@end
